﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using TarreOA.TarreOABLL;
using TarreOA.TarreOAModels;
using TarreOA.TarreOADAL;
using System.Data.SqlClient;

public partial class User_UserEmail_SendEmail : System.Web.UI.Page
{
    private SectionServices sectionService = new SectionServices();
    private UserManager userManager = new UserManager();
    private EmpEmailMappingtbService empEmailMappingtbService = new EmpEmailMappingtbService();

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            this.HyperLink1.Attributes.Add("onclick", "checkEmailTarget('selectedLbx')");
            this.willSelectOneLbx.Attributes.Add("ondblclick", "moveSelectEmp('willSelectOneLbx','selectedLbx','right')");
            this.selectedLbx.Attributes.Add("ondblclick", "moveSelectEmp('selectedLbx','willSelectOneLbx','left')");
        }
        this.fillWillSelectOneLbx();
    }

    //将所有人员名单添加到指定通讯人列表框中
    protected void fillWillSelectOneLbx()
    {
        User curLoginUser = (User) Session["user"];
        this.willSelectOneLbx.Items.Clear();

        SqlConnection sqlConn = null;
        SqlCommand sqlCmd = null;
        SqlDataReader sqlDr = null;
        string state = "";
        try
        {
            sqlConn = SQLManager.GetConn();
            sqlConn.Open();
            sqlCmd = new SqlCommand("select username,loginname from usertb order by userid", sqlConn);
            sqlDr = sqlCmd.ExecuteReader();
            while (sqlDr.Read())
            {
                state = "离线";
                if (!sqlDr["loginname"].ToString().Equals(curLoginUser.LoginName))
                {
                    if (OnlineList.getOnlineUsers()[sqlDr["loginname"].ToString()] != null)
                    {
                        state = "在线";
                    }
                    this.willSelectOneLbx.Items.Add(new ListItem(sqlDr["username"].ToString() + "[" + state + "]", sqlDr["loginname"].ToString()));
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            if (sqlDr != null)
            {
                sqlDr.Close();
                sqlDr.Dispose();
            }
            if (sqlConn != null)
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
                sqlConn.Dispose();
            }
        }

        //List<int> csids = sectionService.findAllChildSectionByBaseSectionId(0);
        //string state = "";
        //foreach(int csid in csids)
        //{
        //    foreach(User user in userManager.findBySectionId(csid))
        //    {
        //        state = "离线";
        //        if(user.UserId != curLoginUser.UserId)
        //        {
        //            if(OnlineList.getOnlineUsers()[user.LoginName] != null)
        //            {
        //                state = "在线";
        //            }
        //            this.willSelectOneLbx.Items.Add(new ListItem(user.UserName + "[" + state + "]", user.LoginName));
        //        }
        //    }
        //}
    }

    //将通知发送给目标人员(针对人员集合)
    protected void addInformToSectionEmp()
    {
        User curLoginUser = (User) Session["user"];
        //string[] emps = Request[this.selectedEmpCollection.ClientID].Split(',');
        string[] emps = Request.Form.GetValues(this.selectedLbx.ClientID);
        DateTime sendDateTime = DateTime.Now;
        FileUploadMappingtbService fileUploadMappingtbService = new FileUploadMappingtbService();
        bool state = false;
        for(int i = 0; i < emps.Length; i++)
        {
            int eid = empEmailMappingtbService.saveEmailInfo(curLoginUser.LoginName, emps[i], this.ftbEmailContent.Text, DateTime.Now);
            if(!"".Equals(this.uploadFilePaths.Value))
            {
                string[] filePaths = this.uploadFilePaths.Value.Split(',');
                for(int j = 0; j < filePaths.Length; j++)
                {
                    string fileName = filePaths[j].Substring(filePaths[j].LastIndexOf('\\') + 1);
                    string suln = fileName.Substring(0, fileName.IndexOf('2'));
                    string iuln = fileName.Substring(fileName.IndexOf('2') + 1, fileName.IndexOf('_') - (fileName.IndexOf('2') + 1));
                    if(suln.Trim().Equals(curLoginUser.LoginName.Trim()) && iuln.Trim().Equals(emps[i].Trim()))
                    {
                        fileUploadMappingtbService.saveUploadFileInfo(suln, iuln, filePaths[j], DateTime.Now, eid);
                    }
                }
            }
            MessageAwoke.Instance().AddToEmail(emps[i], eid);
            //StreamWriter sw = File.AppendText("d:\\error.txt");
            //sw.WriteLine("errir:eid=" + eid);
            //sw.Close();
            if(eid > 0)
            {
                state = true;
            }
        }
        if(state)
        {
            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "", "alert('投递成功！');", true);
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(Page, GetType(), "", "alert('投递失败，请检查网络！');", true);
        }
    }
    protected void btnSendEmail_Click(object sender, EventArgs e)
    {
        this.addInformToSectionEmp();
    }
}
